<template>
  <div class="course-list-container">
    <!-- 搜索框和新增按钮 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="课程名称"
        style="width: 200px; margin-right: 10px;"
        clearable
      />
      <el-select
        v-model="searchMajor"
        placeholder="请选择专业"
        style="width: 180px; margin-right: 10px;"
        clearable
        filterable
        remote
        :remote-method="remoteMethod"
        :loading="majorsLoading"
      >
        <el-option
          v-for="major in majorsForSelect"
          :key="major.id"
          :label="major.name"
          :value="major.name"
        />
      </el-select>
      <el-input
        v-model="searchGrade"
        placeholder="年级（如2024）"
        style="width: 120px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">搜索</el-button>
      <el-button 
        type="primary" 
        @click="handleAdd"
      >
        新增课程
      </el-button>
    </div>

    <!-- 课程列表 -->
    <el-table
      :data="courseList"
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="courseId" label="课程序号" width="150">
        <template #default="scope">
          <span>{{ scope.row.courseId }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="name" label="课程名称" width="250">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="major" label="所属专业" width="200">
        <template #default="scope">
          <span>{{ scope.row.major }}</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="grade" label="年级" width="150">
        <template #default="scope">
          <span>{{ scope.row.grade }}级</span>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" v-if="isAdmin">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="200" v-else>
        <template #default="scope">
          <span style="color: #999;">仅限管理员操作</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { courseApi } from '@/api/courseApi.js'
import { majorApi } from '@/api/majorApi.js'

// 响应式数据
const courseList = ref([])
const majorsForSelect = ref([])
const majorsLoading = ref(false)
const searchKeyword = ref('')
const searchMajor = ref('')
const searchGrade = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)

// 分页信息
const pagination = ref({
  currentPage: 1,
  size: 20,
  total: 0,
  pages: 0
})

// 模拟管理员权限（后续可从用户系统获取）
const isAdmin = ref(true)

// 加载课程列表数据
const loadCourseList = async () => {
  try {
    loading.value = true
    const otherParams = {}
    if (searchKeyword.value) otherParams.name = searchKeyword.value
    if (searchMajor.value) otherParams.major = searchMajor.value
    if (searchGrade.value) otherParams.grade = parseInt(searchGrade.value)
    
    const result = await courseApi.getCourseList({
      currentPage: currentPage.value,
      size: pageSize.value,
      otherParams
    })
    courseList.value = result.list
    pagination.value = result.pagination
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  } finally {
    loading.value = false
  }
}

// 远程模糊查询专业
const remoteMethod = async (query) => {
  if (!query) {
    majorsForSelect.value = []
    return
  }
  majorsLoading.value = true
  try {
    const res = await majorApi.fuzzyQueryMajor(query)
    majorsForSelect.value = res.data || []
  } catch (e) {
    majorsForSelect.value = []
  } finally {
    majorsLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  loadCourseList()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  loadCourseList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadCourseList()
}

// 新增课程
const handleAdd = () => {
  // 跳转到CourseBaseInfo.vue组件进行编辑
  // 通过自定义事件通知父组件切换菜单
  const event = new CustomEvent('menuChange', {
    detail: { menuIndex: 'course-2' }
  })
  window.dispatchEvent(event)
}

// 编辑课程
const handleEdit = (row) => {
  // 跳转到CourseBaseInfo.vue组件进行编辑
  // 通过自定义事件通知父组件切换菜单，并传递课程ID
  const event = new CustomEvent('menuChange', {
    detail: { 
      menuIndex: 'course-2',
      courseId: row.id
    }
  })
  window.dispatchEvent(event)
  
  // 同时更新URL参数，传递课程ID
  const currentUrl = new URL(window.location.href)
  currentUrl.searchParams.set('courseId', row.id)
  window.history.pushState({}, '', currentUrl.toString())
}



// 删除课程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await courseApi.deleteCourse(row.id)
    ElMessage.success('删除成功')
    loadCourseList() // 重新加载数据
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadCourseList()
})
</script>

<style scoped>
.course-list-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 